(function () {
    module.exports = chatSet;

    function chatSet(app) {
        // 立即链接 Websocket
        app.ConnectSocket = function (obj) {
            var that = app;
            if (that.globalData.ws_domain == '' || (that.globalData.chat_config.SocketTask && that.globalData.chat_config.SocketTask.readyState == 1)) {
                return false;
            }
			that.globalData.chat_config.url=that.globalData.ws_domain+'?token='+uni.getStorageSync('token');
            var SocketTask = uni.connectSocket({
                url: that.globalData.chat_config.url,
                success: () => {
                    // console.log('wss 连接成功');
                    uni.onNetworkStatusChange(function (res) {
                        console.log(res.isConnected);
                        console.log(res.networkType);
                    });
                }
            });
            that.globalData.chat_config.SocketTask = SocketTask;
            SocketTask.onMessage((evt) => {
                var msg = JSON.parse(evt.data);

                if (msg.code == 0) {
                    console.log(msg.msg);
                }

                that.handlemsg(msg);
            });
            SocketTask.onOpen(() => {
                that.globalData.chat_config.CurrentRetryCount = 0; // 重新发送所有出错的消息

                if (that.globalData.chat_config.ErrorMsg.length > 0) {
                    for (let i in that.globalData.chat_config.ErrorMsg) {
                        that.ws_send(that.globalData.chat_config.ErrorMsg[i]);
                    }

                    that.globalData.chat_config.ErrorMsg = [];
                }

                if (that.globalData.chat_config.Timer != null) {
                    clearInterval(that.globalData.chat_config.Timer);
                }

                that.globalData.chat_config.Timer = setInterval(that.ws_send, 29999); //定时发送心跳
            });
            SocketTask.onError(function (res) {
                // console.log('wss:onError', res);
            });
            SocketTask.onClose(function (res) {
                // console.log('关闭');

                if (that.globalData.chat_config.Timer != null) {
                    clearInterval(that.globalData.chat_config.Timer);
                }

                if (that.globalData.chat_config.MaxRetryCount) {
                    that.globalData.chat_config.Timer = setInterval(that.retry_webSocket, 3000); //每3秒重新连接一次
                }
            });
        }.bind(app); // 重连wss

        app.retry_webSocket = function (option = {}) {
            var that = app;

            if (that.globalData.chat_config.CurrentRetryCount < that.globalData.chat_config.MaxRetryCount) {
                that.globalData.chat_config.CurrentRetryCount++;
                that.ConnectSocket();
                // console.log('重连 WebSocket 第' + that.globalData.chat_config.CurrentRetryCount + '次');
            } else {
                if (that.globalData.chat_config.Timer != null) {
                    clearInterval(that.globalData.chat_config.Timer);
                }

                if (that.globalData.chat_config.ReConnection) {
                    // console.log('每隔10秒将再次尝试重连 WebSocket');
                    that.globalData.chat_config.Timer = setInterval(that.ConnectSocket, 10000); //每10秒重新连接一次
                }
            }
        }.bind(app); // 发送消息

        app.ws_send = function (message) {
            var that = app;

            if (!message) {
                message = {
                    type: 'ping'
                };
                that.changeTimeText();
            }

            if (that.globalData.chat_config.SocketTask && that.globalData.chat_config.SocketTask.readyState == 1) {
                that.globalData.chat_config.SocketTask.send({
                    data: JSON.stringify(message),
                    success: (res) => {
                        // console.log(res);
                    },
                    fail: (res) => {
                        // console.error(res);
                    }
                });
            } else {
                console.log('消息发送出错', message);
                that.globalData.chat_config.ErrorMsg.push(message);
            }
        }.bind(app); // 处理返回消息

        app.handlemsg = function (ret) {
            var that = app;
            switch (ret.type) {
                case 'login':
                    that.globalData.chat_config.ortherdata = ret.data; // 设置底部菜单的角标

                    //app.setMessageBadge(true); // 获取第一页会话列表

                    that.globalData.chat_config.session_time = 0;
                    that.globalData.chat_config.session_id = 0;
                    that.globalData.chat_config.session_list = null;
					
                    that.ws_send({
                        type: 'sessionlist',
                        session_time: 0,
                        session_id: 0
                    });
                    break;

                case 'session_list':
                    if (ret.code == 0) {
                        that.info(ret.msg);
                        return;
                    } // 处理会话列表

                    that.handle_session_list(ret.data);
                    break;

                case 'msg_list':
                    // 处理聊天记录列表
                    var data = that.handle_msg_list(ret);
					uni.$emit('msg_list_callback',data);

                    break;

                case 'del_session':
                    if (ret.code != 1) {
                        that.info(ret.msg);
                        return false;
                    } // 删除会话

                    var data = that.del_session_list(ret.data);
                    break;

                case 'join_blacklist':
                    if (ret.code != 1) {
                        that.info(ret.msg);
                        return false;
                    } // 拉黑用户会话

                    var data = that.join_blacklist(ret.data);
                    break;

                case 'blacklist':
                    // 黑名单列表
                    if (typeof app.globalData.chat_config.blacklist_callback == 'function') {
                        app.globalData.chat_config.blacklist_callback(ret.data);
                    }

                    break;

                case 'del_blacklist':
                    if (ret.code != 1) {
                        that.info(ret.msg);
                        return false;
                    } // 移除黑名单

                    if (typeof app.globalData.chat_config.del_blacklist_callback == 'function') {
                        app.globalData.chat_config.del_blacklist_callback(ret.data);
                    } // 获取第一页会话列表

                    that.globalData.chat_config.session_time = 0;
                    that.globalData.chat_config.session_id = 0;
                    that.globalData.chat_config.session_list = null;
                    that.ws_send({
                        type: 'sessionlist',
                        session_time: 0,
                        session_id: 0
                    });
                    break;

                case 'new_msg':
                    // 处理会话列表数据
                    that.new_session_list(ret.data); // 如果存在新消息回调函数，直接返回
					uni.$emit('new_msg_callback',ret.data);

                    uni.vibrateLong({
                        success: function () {
                            console.log('震动成功');
							 that.setMessageBadge(true);
                        }
                    });
                    break;

                case 'say':
                    if (ret.code == 0) {
                        that.info(ret.msg);
                        return;
                    }
                    that.new_session_list(ret.data); // 如果存在新消息回调函数，直接返回
					uni.$emit('new_msg_callback',ret.data);
                    break;

                case 'set_read':
                    if (ret.code == 0) {
                        return;
                    }

                    var read_num = 0; // 处理会话列表数据
					
                    var now_data = app.globalData.chat_config.session_list.data;
					
                    for (let index = 0; index < now_data.length; index++) {
                        const element = now_data[index];

                        if (element.id == ret.data.session_id) {
                            read_num = now_data[index].unread_num;
                            now_data[index].unread_num = 0;
                        }
                    }

                    that.globalData.chat_config.session_list.data = now_data;
                    that.globalData.chat_config.ortherdata.unread_num = that.globalData.chat_config.ortherdata.unread_num - read_num;
                    //that.setMessageBadge(true);
                    break;

                default:
                    break;
            }
        }.bind(app); // 发送消息

        app.sendMessage = function (receive_user_id, session_id, content, chat_type = 1) {
            app.ws_send({
                type: 'say',
                receive_user_id: receive_user_id,
                session_id: session_id,
                content: content,
                chat_type: chat_type //类型:1=文字,2=图片,3=房源,4=租房
            });
        }.bind(app);
        
		//文本提示
        app.info = function (msg, cb) {
            uni.showToast({
                title: msg,
                icon: 'none',
                duration: 2000,
                complete: function () {
                    typeof cb == 'function' && cb();
                }
            });
        }.bind(app); // 获取列表数据

        app.get_msg_list = function (session_id, receive_user_id, page) {
            var chat_config = app.globalData.chat_config;
            app.ws_send({
                type: 'msglist',
                page: page,
                session_id: session_id,
                receive_user_id: receive_user_id
            });
        }.bind(app); // 处理一个聊天记录按时间分组

        app.handle_msg_list = function (ret) {
            var res = ret.data;

            if (res.total == 0) {
                return {
                    data: res,
                    images_arr: [],
                    receive_user: ret.receiveuser
                };
            }

            var array = [];
            var new_arr = [];
            var min_time = res.data[res.data.length - 1].createtime;
            var min_time_text = res.data[res.data.length - 1].createtime_text;
            array[min_time_text] = [];
            var images_arr = [];

            for (let index = res.data.length - 1; index >= 0; index--) {
                const v = res.data[index];

                if (v.chat_type == 2) {
                    images_arr.push(v.content_text);
                } // 处理表情包

                v.content_text = v.chat_type == 1 ? app.changeEmotion(v.content_text) : v.content_text; // 如果当前时间和最早时间相差不超过10分钟，就分为一组

                if (v.createtime - min_time <= 600) {
                    array[min_time_text].push(v);
                } else {
                    min_time = v.createtime;
                    min_time_text = v.createtime_text;
                    array[min_time_text] = [];
                    array[min_time_text].push(v);
                }
            }

            for (const key in array) {
                new_arr.push({
                    time: key,
                    data: array[key]
                });
            }

            res.data = new_arr;
            return {
                data: res,
                images_arr: images_arr,
                receive_user: ret.receiveuser
            };
        }.bind(app);

        app.handle_msg_data = function (data) {
            var new_arr = [];
            var images_arr = [];

            if (data.chat_type == 2) {
                images_arr.push(data.content_text);
            } // 处理表情包

            data.content_text = data.chat_type == 1 ? app.changeEmotion(data.content_text) : data.content_text;
            new_arr.push({
                time: data.createtime_text,
                data: [data]
            });
            return {
                data: new_arr,
                images_arr: images_arr
            };
        }.bind(app); // 处理一个聊天列表分页

        app.handle_session_list = function (data) {
            console.log(data);
            var chat_config = app.globalData.chat_config;

            if (chat_config.session_time == 0 && chat_config.session_id == 0 && (!chat_config.session_list || chat_config.session_list.total == 0)) {
                app.globalData.chat_config.session_list = data;
            } else {
                var now_data = app.globalData.chat_config.session_list.data;
                now_data=now_data.concat(data.data);
                data.data = now_data;
                app.globalData.chat_config.session_list = data;
            }
            app.set_new_min_time();
			uni.$emit('session_list_callback',{});
        }.bind(app); // 删除一条聊天数据

        app.del_session_list = function (data) {
            var now_data = app.globalData.chat_config.session_list.data;

            for (let index = 0; index < now_data.length; index++) {
                const element = now_data[index];

                if (data.session_id == element.id) {
                    now_data.splice(index, 1);
                }
            }

            app.globalData.chat_config.session_list.data = now_data;
			uni.$emit('session_list_callback',{});
        }.bind(app); // 拉黑用户

        app.join_blacklist = function (data) {
            var now_data = app.globalData.chat_config.session_list.data;

            for (let index = 0; index < now_data.length; index++) {
                const element = now_data[index];

                if (data.session_id == element.id) {
                    now_data.splice(index, 1);
                }
            }

            app.globalData.chat_config.session_list.data = now_data;
			uni.$emit('session_list_callback',{});
        }.bind(app); // 新增一个聊天数据,只有新消息的时候才会用到这个函数

        app.new_session_list = function (data) {
            var now_data = app.globalData.chat_config.session_list.data;
            var user_id = app.globalData.chat_config.ortherdata.user_info.user_id;
            var unread_num = app.globalData.chat_config.ortherdata.unread_num;
            var is_exist = false; // 判断是否存在该会话

            for (let index = 0; index < now_data.length; index++) {
                const element = now_data[index];

                if (element.id == data.session_id) {
                    is_exist = true;
                    var session_data = now_data[index];
                    session_data.newmsg.content_text2 = data.content_text2;
                    session_data.updatetime_text = data.createtime_text;
                    session_data.updatetime = data.createtime; // 判断未读个数

                    if (user_id == data.receive_user_id) {
                        unread_num++;
                        session_data.unread_num++;
                    }

                    now_data.splice(index, 1);
                    now_data.unshift(session_data);
                }
            } // 创建新的会话数据

            if (!is_exist) {
                var session_data = {
                    id: data.session_id,
                    receive_user_id: data.receive_user_id,
                    send_user_id: data.send_user_id,
                    receiveuser: data.receiveuser,
                    senduser: data.senduser,
                    updatetime_text: data.createtime_text,
                    updatetime: data.createtime,
                    unread_num: user_id == data.receive_user_id ? 1 : 0,
                    see_type: 0,
                    newmsg: {
                        content_text2: data.content_text2
                    }
                };
                now_data.unshift(session_data);

                if (user_id == data.receive_user_id) {
                    unread_num++;
                }
            }

            app.globalData.chat_config.session_list.data = now_data;
            app.globalData.chat_config.ortherdata.unread_num = unread_num;
			uni.$emit('session_list_callback',{});
        }.bind(app); // 获取最小时间和id

        app.set_new_min_time = function () {
            var session_list_data = app.globalData.chat_config.session_list.data;
            var len = session_list_data.length;
            app.globalData.chat_config.session_time = len > 0 ? session_list_data[len - 1].updatetime : 0;
            app.globalData.chat_config.session_id = len > 0 ? session_list_data[len - 1].id : 0;
        }.bind(app); // 设置底部菜单角标 有底部的页面onshow里都要调用该方法

        app.setMessageBadge = function (is_need_check = false) {
            if (!app.globalData.chat_config.ortherdata) {
                return false;
            }

            var unread_num = app.globalData.chat_config.ortherdata.unread_num; // 判断当前页面是否为tabbar页面，如果是，就设置

            if (is_need_check && getCurrentPages().length>0) {
                var pages = getCurrentPages(); //获取加载的页面
                var currentPage = pages[pages.length - 1]; //获取当前页面的对象
                var url = currentPage.route; //当前页面url

                var arr = ['pages/home/index/index', 'pages/rental/renting_list/renting_list', 'pages/home/information/information', 'pages/home/mine1/mine1', 'pages/home/chatlist/chatlist'];

                if (arr.indexOf(url) == -1) {
                    return false;
                }
            }
            if (unread_num > 0) {
                uni.setTabBarBadge({
                    index: 3,
                    text: '' + unread_num
                });
            } else {
                uni.hideTabBarRedDot({
                    index: 3
                });
            }
        }.bind(app);

        app.changeEmotion = function (contents) {
            var emotions = app.globalData.chat_config.ortherdata.chat_memes;
            var pattern1 = /\[[\u4e00-\u9fa5]+\]/g;
            var pattern2 = /\[[\u4e00-\u9fa5]+\]/;

            if (contents) {
                contents = contents.replace(new RegExp(/\<br>/, 'g'), '\n');
                contents = contents.replace(new RegExp(/\<br\/>/, 'g'), '\n');
            }

            var content = contents.match(pattern1);
            var str = contents;
            var now_str = contents;
            var arr = [];
            if (content == null)
                return [
                    {
                        type: 1,
                        value: str
                    }
                ];

            for (var i = 0; i < content.length; i++) {
                var src = '';

                for (var j = 0; j < emotions.length; j++) {
                    if (emotions[j].name == content[i]) {
                        src = emotions[j].image;
                        break;
                    }
                }

                if (!now_str) {
                    break;
                }

                var has_i = now_str.indexOf(content[i]);

                if (has_i != -1) {
                    arr.push({
                        type: 1,
                        value: now_str.substring(0, Number(has_i))
                    });
                    arr.push({
                        type: 2,
                        value: src
                    });
                    now_str = now_str.substring(Number(has_i) + Number(content[i].length));

                    if (i == content.length - 1) {
                        arr.push({
                            type: 1,
                            value: now_str
                        });
                    }
                }
            }

            return arr;
        }.bind(app);

        app.changeTimeText = function () {
            if (!app.globalData.chat_config.session_list) {
                return false;
            }

            var now_data = app.globalData.chat_config.session_list.data;

            for (let index = 0; index < now_data.length; index++) {
                now_data[index].updatetime_text = formatMsgTime(now_data[index].updatetime * 1000);
            }

            app.globalData.chat_config.session_list.data = now_data;
			uni.$emit('session_list_callback',{});
        }.bind(app);
    }
})();

function formatMsgTime(timestamp) {
    var mistiming = Math.round((Date.now() - timestamp) / 1000);
    var arrr = ['年', '个月', '星期', '天', '小时', '分钟', '秒'];
    var arrn = [31536000, 2592000, 604800, 86400, 3600, 60, 1];

    for (var i = 0; i < arrn.length; i++) {
        var inm = Math.floor(mistiming / arrn[i]);

        if (inm != 0) {
            return inm + arrr[i] + '前';
        }
    }
}
